package com.yangzheandroid.rxmvp.http.interceptor;


import com.yangzheandroid.retrofitutils.utils.SharePreUtils;
import com.yangzheandroid.retrofitutils.utils.StringUtils;
import com.yangzheandroid.rxmvp.APP;
import com.yangzheandroid.rxmvp.http.HttpClients;
import com.yangzheandroid.rxmvp.utils.CommonUtils;
import com.yangzheandroid.rxmvp.utils.MD5Utils;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
 * =========================================================
 *
 *  版权: 河北骏昌科技公司开发 版权所有(c)
 *
 *  作者:Yangjilai
 *
 *  版本: 1.0.0
 *
 *
 *  创建日期 : 2017/3/6  17:56
 *
 *
 * 描述:
 *
 *
 * 修订历史:
 *
 * =========================================================
 */
public class BasicParamsInterceptor implements Interceptor {
    private static final String TAG = BasicParamsInterceptor.class.getSimpleName();

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();

        // 自定义User-Agent
        requestBuilder.addHeader("User-Agent", HttpClients.ua);


        String userId = SharePreUtils.getsPreString(APP.getInstance(), "userkey", "");
        String token = SharePreUtils.getsPreString(APP.getInstance(), "tokenkey", "");

        if (!StringUtils.isEmpty(userId) && !StringUtils.isEmpty(token)) {
            String nonce = CommonUtils.getRandomString(16);
            long timestamp = System.currentTimeMillis();
            String sign = MD5Utils.md5(userId + token + nonce + timestamp);

            HttpUrl httpUrl = request.url().newBuilder()
                    .addQueryParameter("userId", userId)
                    .addQueryParameter("nonce", nonce)
                    .addQueryParameter("timestamp", timestamp + "")
                    .addQueryParameter("sign", sign)
                    .build();

            requestBuilder.url(httpUrl);
        }


        return chain.proceed(requestBuilder.build());
    }
}
